package net.cjw.initsb.controller.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import io.swagger.annotations.Api;
import net.cjw.initsb.common.ServiceResult;
import net.cjw.initsb.dao.ErrorLogMapper;
import net.cjw.initsb.service.FileServiceI;

@Api(description = "文件")
@Controller
@RequestMapping("file")
public class FileController {

	private Logger logger = LoggerFactory.getLogger(FileController.class);

	@Value("${file.save.path}")
	private String fileSavePath;

	@Autowired
	private FileServiceI fileServiceI;

	// 图片查看 使用Spring正则表达式(SpEL)解决点丢失问题
	@RequestMapping(value = "/image/{fileName:.+}", method = RequestMethod.GET)
	public void findImage(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value = "fileName", required = true) String fileName) {
		logger.info("访问  fileName: " + fileName);
		String datePath = fileName.split("_")[0];
		logger.info("datePath: " + datePath);
		logger.info("fileSavePath + datePath + File.separator + fileName: " + fileSavePath + datePath + File.separator
				+ fileName);
		File file = new File(fileSavePath + datePath + File.separator + fileName);
		if (!file.exists()) {
			logger.info("文件不存在");
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ "/";
			logger.info("basePath: " + basePath);
			// http: // testfile.cjwdemo.com/
			try {
				response.sendRedirect(basePath + "common/image/not_image.jpg");
				return;
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		try {
			// 返回这个文件
			byte[] bs = new byte[1024];
			FileInputStream fi = new FileInputStream(file);
			response.setHeader("Content-Type", "image/jpeg");// 设置响应的媒体类型，这样浏览器会识别出响应的是图片

			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			int state;
			while (-1 != (state = fi.read(bs))) {
				bao.write(bs);
			}
			response.getOutputStream().write(bao.toByteArray());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 文件下载 使用Spring正则表达式(SpEL)解决点丢失问题
	@RequestMapping(value = "download/{fileName:.+}", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value = "fileName", required = true) String fileName) {
		logger.info("访问  fileName: " + fileName);
		String datePath = fileName.split("_")[0];
		logger.info("fileSavePath + datePath + File.separator + fileName: " + fileSavePath + datePath + File.separator
				+ fileName);
		File file = new File(fileSavePath + datePath + File.separator + fileName);
		if (!file.exists()) {
			logger.info("文件不存在");
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ "/";
			logger.info("basePath: " + basePath);
			// http://testfile.cjwdemo.com/
			try {
				// response.sendRedirect(basePath +
				// "common/txt/not_find_file.txt");
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				response.getWriter().println("找不到文件");
				return;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			// 返回这个文件
			byte[] bs = new byte[1024];
			FileInputStream fi = new FileInputStream(file);
			// 设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			int state;
			while (-1 != (state = fi.read(bs))) {
				bao.write(bs);
			}
			response.getOutputStream().write(bao.toByteArray());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 单文件上传
	@PostMapping("upload_one_file")
	@ResponseBody
	public ServiceResult<String> upload_one_file(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return ServiceResult.buildError("上传文件为空");
		}

		return fileServiceI.uploadOneFile(file);

	}

	// 多文件上传 不推荐使用
	@PostMapping("upload_more_file")
	@ResponseBody
	public ServiceResult<String> upload_more_file(HttpServletRequest request) {

		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		if (files.isEmpty()) {
			return ServiceResult.buildError("上传文件为空");
		}
		return fileServiceI.uploadMoreFile(files);
		
	} 

}
